var createError = require('http-errors');
var bodyparser = require('body-parser');
var session = require('express-session');
var express = require('express');
var ejs = require('ejs');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var pjax = require('express-pjax');
var indexRouter = require('./routes/index');
var homeRouter = require('./routes/home');
const apiRouter = require('./controller');
const userRouter = require('./controller/user');
const shopRouter = require('./controller/shop');
require('./service/drawCode');

// var usersRouter = require('./routes/users');
// var errorRouter = require('./routes/error');
var secretOrPrivateKey = "rbydxhq" 
var app = express();
app.use(pjax());
// view engine setup
app.engine('html',ejs.__express);
app.set('view engine', 'html');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// 使用 session 中间件
app.use(session({
    secret : 'secret', // 对session id 相关的cookie 进行签名
    resave : true,
    saveUninitialized: false, // 是否保存未初始化的会话
    cookie : {
        maxAge : 1000 * 60 * 60, // 设置 session 的有效时间，单位毫秒
    },
}));
app.use('/', indexRouter);
app.use('/admin', homeRouter);
app.use('/api', apiRouter);
app.use('/user', userRouter);
app.use('/shop', shopRouter);


// error handler
//加载ueditor 模块
var ueditor = require("ueditor");

// app.use(function (err, req, res, next) {
//    console.log(err.name);
//   if (err.name === 'UnauthorizedError') {   
//       //  这个需要根据自己的业务逻辑来处理（ 具体的err值 请看下面）
//     return res.status(401).send('invalid token...');
//   }
// });
//使用模块
app.use("/ueditor/ue", ueditor(path.join(__dirname, 'public'), function (req, res, next) {
    // ueditor 客户发起上传图片请求
    if (req.query.action === 'uploadimage') {
        var foo = req.ueditor;
 
        var imgname = req.ueditor.filename;
 
        var img_url = '/images';
        res.ue_up(img_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
        res.setHeader('Content-Type', 'text/html');//IE8下载需要设置返回头尾text/html 不然json返回文件会被直接下载打开
    }
    //  客户端发起图片列表请求
    else if (req.query.action === 'listimage') {
        var dir_url = '/images/';
        res.ue_list(dir_url); // 客户端会列出 dir_url 目录下的所有图片
    }
    // 客户端发起其它请求
    else {
        res.setHeader('Content-Type', 'application/json');
        res.redirect('/wap/static/lib/ueditor/php/config.json');
    }
}));
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
// app.use('/error',errorRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
   //判断用户是否登陆
   res.render('404.html');
   next();
});
// app.use(expressJWT({
//     secret: secretOrPrivateKey   
// }).unless({
//     path: ['/getToken']  //除了这个地址，其他的URL都需要验证
// }));


module.exports = app;

